package com.mzba.place.ui;

import java.util.HashMap;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.Geometry;
import com.baidu.mapapi.map.Graphic;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.mzba.place.BasicActivity;
import com.mzba.place.PlaceApplication;
import com.mzba.place.R;
import com.mzba.place.adapter.MyArrayAdapter;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
/**
 * 
 * @author 06peng
 *
 */
public class SettingCaustionsActivity extends BasicActivity implements Callback {
	
	private MapView mMapView;
	private PlaceApplication app;

	private LocationClient mLocClient;

	private Drawable myLocation;
	private MapController mMapController = null;
	private boolean isMoved;
	private int mLastMotionX, mLastMotionY;
	private int zoomLevel = 14;
	private int latitude;
	private int longitude;
	// 移动的阈值
	private static final int TOUCH_SLOP = 20;
	private Handler handler;
	public MKSearch mSearch = null;

	GraphicsOverlay graphicsOverlay = null;

	private TextView tv_location;
	private TextView tv_reporttype;
	private SpannableString ss;
    /**
     * 地图范围
     */
	private Spinner rangeSpinner;
	private ArrayAdapter<CharSequence> rangeAdapter;
	private EditText ed_address;
	private ImageView iv_address;
	/**
	 * 类型
	 */
	private Spinner reportTypeSpinner;
	private MyArrayAdapter reportTypeAdapter;

	/**
	 * 选中的半径 默认是3
	 */
	private double raidus;
	/**
	 * 
	 */
	private String raidusString[];
	private GeoPoint currentPoint;
	
	
	private final int menu_confirm = 5;
	private final int init_caustions = 6;
	private final int show_positoin = 7;
	private String place;
	
	private int radius;
	private int type_id;
	private ScrollView scrollView;
	private String response;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		handler = new Handler(this);
		setSupportProgressBarIndeterminateVisibility(false);
		setContentView(R.layout.framgnent_setting_map);
		actionBar.show();
		actionBar.setDisplayShowTitleEnabled(true);
		setTitle("设置区域和类型");
		app = (PlaceApplication) getApplication();
        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(this);
            app.mBMapManager.init(PlaceApplication.strKey, new PlaceApplication.MyGeneralListener());
        }
        
		raidusString = getResources().getStringArray(R.array.Range);
		mLocClient = app.mLocationClient;
		app.getMyListener().setHander(handler);

		myLocation = getResources().getDrawable(R.drawable.ic_map_current_position);
		radius = getIntent().getIntExtra("radius", 0);
		type_id = getIntent().getIntExtra("type_id", 0);
		place = getIntent().getStringExtra("place");
		latitude = getIntent().getIntExtra("lat", 0);
		longitude = getIntent().getIntExtra("lng", 0);
		
		initView();
		
		System.out.println("++++++++++++" + latitude + ";" + longitude);
		if (latitude == 0 || longitude == 0) {
			new Thread() {
				public void run() {
					setLocationOption();
					if (mLocClient != null && mLocClient.isStarted()) {
						mLocClient.requestLocation();
					} else {
						mLocClient.start();
						mLocClient.requestLocation();
					}
				};
			}.start();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (menu != null) {
			menu.clear();
			menu.add(0, menu_confirm, 0, "设置").setIcon(R.drawable.abs__ic_cab_done_holo_dark)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		}
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case menu_confirm:
			setAlarmMap();
			break;
		default:
			break;
		}
		return false;
	}
	
	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setCoorType("bd09ll");	
		option.setAddrType("all");
		option.setScanSpan(0);
		option.setPriority(LocationClientOption.GpsFirst);
		option.setPoiNumber(10);
		option.disableCache(true);
		mLocClient.setLocOption(option);
	}

	private void initView() {
		mMapView = (MapView) findViewById(R.id.bmapView);
		tv_location = (TextView) findViewById(R.id.tv_location_point);
		tv_reporttype = (TextView) findViewById(R.id.tv_report_type_point);
		rangeSpinner = (Spinner) findViewById(R.id.sn_address);
		ed_address = (EditText) findViewById(R.id.et_address);
		iv_address = (ImageView) findViewById(R.id.iv_address);
		scrollView = (ScrollView)findViewById(R.id.scrollview);
		String text = this.getString(R.string.location_point);

		ss = new SpannableString(text);
		ss.setSpan(new RelativeSizeSpan(1.2f), 0, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.setting_green)), 8, 23, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		tv_location.setText(ss);

		text = this.getString(R.string.reporttype_point);
		ss = new SpannableString(text);
		ss.setSpan(new RelativeSizeSpan(1.2f), 0, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.setting_green)), 7, 20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		tv_reporttype.setText(ss);

		rangeAdapter = ArrayAdapter.createFromResource(this, R.array.distanceRange, R.layout.spinner_item);
		rangeAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
		rangeSpinner.setAdapter(rangeAdapter);
		rangeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				TextView tv = (TextView) arg1;
				if (tv != null) {
					tv.setTextColor(android.graphics.Color.BLACK);
				}
				raidus = Double.parseDouble(raidusString[arg2]) * 1000;
				testCircleClick(currentPoint, raidus);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});
		int spinnerPosition;
		switch (radius) {
		case 0:
			spinnerPosition = rangeAdapter.getPosition(rangeAdapter.getItem(2));
			rangeSpinner.setSelection(spinnerPosition);
			break;
		case 1:
			spinnerPosition = rangeAdapter.getPosition(rangeAdapter.getItem(0));
			rangeSpinner.setSelection(spinnerPosition);
			break;
		case 2:
			spinnerPosition = rangeAdapter.getPosition(rangeAdapter.getItem(1));
			rangeSpinner.setSelection(spinnerPosition);
			break;
		case 3:
			spinnerPosition = rangeAdapter.getPosition(rangeAdapter.getItem(2));
			rangeSpinner.setSelection(spinnerPosition);
			break;
		case 5:
			spinnerPosition = rangeAdapter.getPosition(rangeAdapter.getItem(3));
			rangeSpinner.setSelection(spinnerPosition);
			break;
		case 10:
			spinnerPosition = rangeAdapter.getPosition(rangeAdapter.getItem(4));
			rangeSpinner.setSelection(spinnerPosition);
			break;
		default:
			break;
		}
		reportTypeSpinner = (Spinner) findViewById(R.id.report_type_spinner);
		reportTypeAdapter = new MyArrayAdapter(this, R.layout.spinner_item);
		reportTypeAdapter.addAll(getResources().getStringArray(R.array.reportType));
		reportTypeAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
		reportTypeSpinner.setAdapter(reportTypeAdapter);

//		int spinnerPosition1 = reportTypeAdapter.getPosition(reportTypeAdapter.getItem(0));
		reportTypeSpinner.setSelection(type_id);
		reportTypeSpinner.setSelected(true);
		initMap();

	}

	private void initMap() {
		mMapController = mMapView.getController();
		mMapController.enableClick(true);
		mMapController.setZoom(zoomLevel);
		mMapView.setDoubleClickZooming(true);
		mMapView.setOnTouchListener(mapTouchListener);
		mSearch = new MKSearch();
		initMKSearch();
		graphicsOverlay = new GraphicsOverlay(mMapView);
		mMapView.getOverlays().add(graphicsOverlay);
		iv_address.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mSearch.geocode(ed_address.getText().toString(), "");
			}
		});
	}

	private OnTouchListener mapTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int x = (int) event.getX();
			int y = (int) event.getY();
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				scrollView.requestDisallowInterceptTouchEvent(true);
				isMoved = false;
				mLastMotionX = x;
				mLastMotionY = y;
				mMapView.postDelayed(mLongPressRunnable, 1000);
				break;
			case MotionEvent.ACTION_MOVE:
				scrollView.requestDisallowInterceptTouchEvent(true);
				if (isMoved)
					break;

				if (Math.abs(mLastMotionX - x) > TOUCH_SLOP || Math.abs(mLastMotionY - y) > TOUCH_SLOP) {
					isMoved = true;
					mMapView.removeCallbacks(mLongPressRunnable);
				}
				break;
			case MotionEvent.ACTION_UP:
				scrollView.requestDisallowInterceptTouchEvent(false); 
				mMapView.removeCallbacks(mLongPressRunnable);
				break;
			default:
				break;
			}
			return false;
		}
	};
	
	/** 长按 */
	private Runnable mLongPressRunnable = new Runnable() {
		@Override
		public void run() {
			final GeoPoint pt = mMapView.getProjection().fromPixels((int) mLastMotionX, (int) mLastMotionY);
			mSearch.reverseGeocode(pt);
		}
	};

	@Override
	public boolean handleMessage(Message msg) {
		try {
			switch (msg.what) {
			case AppContext.LOCATE:
				latitude = (int) (app.latitude * 1E6);
				longitude = (int) (app.longitude * 1E6);
				if (latitude != 0 && longitude != 0) {
					GeoPoint pt = new GeoPoint(latitude, longitude);
					currentPoint = pt;
					mSearch.reverseGeocode(pt);
					mMapController.animateTo(pt);
					OverlayItem item = new OverlayItem(pt, null, null);
					ItemizedOverlay<OverlayItem> overlay = new ItemizedOverlay<OverlayItem>(myLocation, mMapView);
					overlay.removeAll();
					overlay.addItem(item);
					mMapView.getOverlays().clear();
					mMapView.getOverlays().add(overlay);
					mMapView.refresh();
					mSearch.reverseGeocode(pt);
				}
				break;
			case menu_confirm:
				if (response != null) {
					Toast.makeText(this, "设置成功！", Toast.LENGTH_LONG).show();
				}
				setResult(RESULT_OK);
				finish();
				break;
			case show_positoin:
				GeoPoint pt = new GeoPoint(latitude, longitude);
				currentPoint = pt;
				mMapController.animateTo(pt);
				OverlayItem item = new OverlayItem(pt, null, null);
				ItemizedOverlay<OverlayItem> overlay = new ItemizedOverlay<OverlayItem>(myLocation, mMapView);
				overlay.removeAll();
				overlay.addItem(item);
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(overlay);
				testCircleClick(currentPoint, raidus);
				mMapView.refresh();
				mMapController.setCenter(currentPoint);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	private void initMKSearch() {
		mSearch.init(app.mBMapManager, new MKSearchListener() {

			@Override
			public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) { }

			@Override
			public void onGetTransitRouteResult(MKTransitRouteResult res, int error) { }

			@Override
			public void onGetSuggestionResult(MKSuggestionResult res, int error) { }

			@Override
			public void onGetPoiResult(MKPoiResult res, int type, int error) { }

			@Override
			public void onGetPoiDetailSearchResult(int res, int error) { }

			@Override
			public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) { }

			@Override
			public void onGetBusDetailResult(MKBusLineResult res, int error) { }

			@Override
			public void onGetAddrResult(MKAddrInfo res, int error) {
				try {
					if (error != 0) {
						if (error == 100) {
							Toast.makeText(SettingCaustionsActivity.this, "解析失败,请正确输入地址：如XXX市XXX", Toast.LENGTH_LONG).show();
							return;
						}
						return;
					}
					if (res.geoPt != null) {
						latitude = res.geoPt.getLatitudeE6();
						longitude = res.geoPt.getLongitudeE6();
						currentPoint = res.geoPt;
						place = res.strAddr;
						OverlayItem item = new OverlayItem(res.geoPt, null, null);
						ItemizedOverlay<OverlayItem> overlay = new ItemizedOverlay<OverlayItem>(myLocation, mMapView);
						overlay.removeAll();
						overlay.addItem(item);
						mMapView.getOverlays().clear();
						mMapView.getOverlays().add(overlay);
						mMapView.refresh();
						testCircleClick(currentPoint, raidus);
						mMapController.setCenter(currentPoint);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});
	}

	@Override
	public void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	public void onResume() {
		mMapView.onResume();
		super.onResume();
		new Thread() {
			public void run() {
				try {
					Thread.sleep(500);
					handler.sendEmptyMessage(show_positoin);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	/**
	 * 画圆
	 * 
	 * @param pt1
	 * @param raidus
	 */
	public void testCircleClick(GeoPoint pt1, double raidus) {

		graphicsOverlay.removeAll();
		// 构建点并显示
		Geometry circleGeometry = new Geometry();

		circleGeometry.setCircle(pt1, (int) raidus);

		Symbol circleSymbol = new Symbol();
		Symbol.Color circleColor = circleSymbol.new Color();
		circleColor.red = 0;
		circleColor.green = 255;
		circleColor.blue = 0;
		circleColor.alpha = 126;
		circleSymbol.setSurface(circleColor, 1, 3);

		Graphic circleGraphic = new Graphic(circleGeometry, circleSymbol);
		graphicsOverlay.setData(circleGraphic);
		mMapView.getOverlays().clear();
		mMapView.getOverlays().add(graphicsOverlay);
		mMapView.refresh();
	}

	@Override
	public void execute(int mes, Object obj) {
		HashMap<String, String> map;
		switch (mes) {
		case menu_confirm:
			String range = raidusString[rangeSpinner.getSelectedItemPosition()];
			map = new HashMap<String, String>();
			map.put("auth_token", AppContext.getInstance().getAuthToken());
			map.put("place", place);
			map.put("longitude", String.valueOf(longitude / 1E6));
			map.put("latitude", String.valueOf(latitude / 1E6));
			map.put("radius", range);
			map.put("type_id", String.valueOf(reportTypeSpinner.getSelectedItemPosition()));
			map.put("from", "android_app");
			response = HttpUtils.doPost(this, UrlConfig.cautions, map);
			handler.sendEmptyMessage(menu_confirm);
			break;
		case init_caustions:
			
			break;
		default:
			break;
		}
	}

	public void setAlarmMap(){
		UICore.eventTask(this, this, menu_confirm, null, true);
	}

}
